<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>排序</title>
    </head>
    <body>
        <script>
            //冒泡排序
            function maopao(arr) {
                for (let i = 0; i < arr.length - 1; i++) {
                    //每一轮需要比较次数 -i次数 有效的控制了每一轮的无效比对次数
                    for (let j = 0; j < arr.length - 1 - i; j++) {
                        if (arr[j] > arr[j + 1]) {
                            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
                        }
                    }
                }
                return arr;
            }
            // console.log(maopao([4, 6, 1, 7, 2, 9]));
            function merger(arr) {
                if (arr.length > 1) {
                    let a = Math.floor(arr.length / 2);
                    let left = merger(arr.slice(0, a));
                    let right = merger(arr.slice(a, arr.length));
                    let res = mergeAry(left, right);
                    console.log("res", res);
                }
                return arr;
            }
            function mergeAry(left, right) {
                let newAry = [];
                //记录right的数组下标
                let i = 0;
                //记录right的数组下标
                let j = 0;
                while (i > left.length && j < right.length) {
                    left[i] < right[j]
                        ? newAry.push(left[i++])
                        : newAry.push(right[j++]);
                }
                //合并逻辑
                return newAry.concat(
                    //i或者j的值直接代表所对应的数组是否所有的值都已经对比完毕
                    i >= left.length ? right.slice(j) : left.slice(i)
                );
            }
            console.log(merger([4, 2, 7, 5, 3, 1, 9, 8]));
        </script>
    </body>
</html>
